package com.killer.db.controller;

import com.killer.common.entity.PageResult;
import com.killer.common.entity.Result;
import com.killer.common.entity.BaseEntity;
import com.killer.db.service.IBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

public class BaseController<M extends IBaseService<T>, T extends BaseEntity> {

    @Autowired
    protected M baseService;

    @PostMapping("/add")
    public Result add(@RequestBody T t){
        baseService.save(t);
        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody T t) {
        if (t.getId() == null) {
            throw new RuntimeException("id不能为空");
        }

        baseService.updateById(t);
        return Result.success();
    }

    @PostMapping("/delete")
    public Result delete(@RequestParam Long id) {
        baseService.removeById(id);
        return Result.success();
    }

    @GetMapping("/findById")
    public Result<T> findById(@RequestParam Long id) {
        T t = baseService.getById(id);
        return Result.success(t);
    }

    @GetMapping("/search")
    public Result<List<T>> search(@RequestParam Map<String, Object> searchMap) {
        List<T> list = baseService.search(searchMap);
        return Result.success(list);
    }

    @GetMapping("/findPage/{pageNum}/{pageSize}")
    public Result<PageResult<T>> findPage(@RequestParam Map<String, Object> searchMap,
                                          @PathVariable("pageNum")Integer pageNum,
                                          @PathVariable("pageSize")Integer pageSize) {
        PageResult<T> pageResult = baseService.findPage(searchMap, pageNum, pageSize);
        return Result.success(pageResult);
    }

    @GetMapping("/count")
    public Result<Integer> countByCondition(@RequestParam Map<String, Object> searchMap) {
        Integer count = baseService.countByCondition(searchMap);
        return Result.success(count);
    }

}
